package com.zkh.myutils.database.dbpool;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

import javax.sql.DataSource;

import com.zkh.myutils.database.DatabaseException;

/**
 * 数据库池数据源对象
 * @author zkh
 */
public final class DbPoolDataSource implements DataSource {
	//连接池对象
	private final Pools pools;
	
	/**
	 * 创建数据源
	 */
	public DbPoolDataSource(String key) {
		try {
			pools = new Pools(key);
		} catch (SQLException e) {
			throw new DatabaseException("数据源创建失败，请检查数据库配置", e);
		}
	}

	/**
	 * 从默认数据源中获取一个连接
	 */
	public Connection getConnection() throws SQLException {
		//加锁
		synchronized (pools) {
			return pools.getConnection();
		}
	}

	/**
	 * 获取单个连接，与连接池无关
	 */
	public Connection getConnection(String username, String password) throws SQLException {
		synchronized ((username + password).intern()) {
			return pools.getConnection(username, password);
		}
	}
	
	/**
	 * 获取数据源配置信息
	 */
	public DataBaseInfo getDataBaseInfo() {
		return pools.getDataBaseInfo();
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return null;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {

	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {

	}

	@Override
	public int getLoginTimeout() throws SQLException {
		return 0;
	}

	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return null;
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return false;
	}

}
